package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.core.service.base.ManageService;
import cc.rengu.igas.bsps.facade.request.GetUserAuthInfoRequest;
import cc.rengu.igas.bsps.facade.response.GetUserAuthInfoResponse;
import cc.rengu.igas.channel.wechat.facade.base.Header;
import cc.rengu.igas.channel.wechat.facade.request.WechatGetOpenIdRequest;
import cc.rengu.igas.channel.wechat.facade.response.WechatGetOpenIdResponse;
import cc.rengu.igas.channel.wechat.facade.result.Result;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.ChannelCallCfg;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 获取用户授权信息
 *
 * @author zhangxuran（联调修改）
 * @version 1.0
 * @date 2020.04.12
 */
public class GetUserAuthInfoService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        GetUserAuthInfoRequest request = new GetUserAuthInfoRequest();
        ConvertUtil.convertOutput(request);
        return request;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {

        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        GetUserAuthInfoRequest getUserAuthInfoRequest = (GetUserAuthInfoRequest) request;
        String instId = getUserAuthInfoRequest.getHeader().getInstId();
        String authCode = getUserAuthInfoRequest.getCode();
        if (StringUtil.isEmptyOrNull(instId) || StringUtil.isEmptyOrNull(authCode)) {
            rglog.error("参数必填性校验失败！instId:<{}>,authCode:<{}>", instId, authCode);
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        GetUserAuthInfoResponse response = new GetUserAuthInfoResponse();
        WechatGetOpenIdRequest wechatGetOpenIdRequest = new WechatGetOpenIdRequest();

        List<ChannelCallCfg> channelCallCfgList = txnInfo.getChannelCallCfgList();
        List<ChannelCallCfg> msgDstchannelCallCfgList = channelCallCfgList.stream().filter(item -> item.getCallChannelId().equals("WXZF")).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(msgDstchannelCallCfgList)) {
            rglog.error("微信通道交易未配置！");
            throw new BizException(RespCodeEnum.CHANNEL_TXN_NOT_SUPPORTED.getRespCode(), RespCodeEnum.CHANNEL_TXN_NOT_SUPPORTED.getRespDesc());
        }
        ChannelCallCfg channelCallCfg = msgDstchannelCallCfgList.get(0);

        Header header = new Header();
        header.setInstId(instId);
        header.setVersion("1.0.0");
        header.setTransTime(DateUtil.getCurrentTime());
        header.setTransDate(DateUtil.getCurrentDate());
        header.setSrcSysId(AppParamConstant.SYS_ID);
        header.setChanlId(channelCallCfg.getMsgSrcId());
        header.setBizType(channelCallCfg.getBizType());
        header.setTxnNum(channelCallCfg.getCallChannelTxn());
        header.setTraceNo(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM));
        wechatGetOpenIdRequest.setHeader(header);

        wechatGetOpenIdRequest.setAuthCode(getUserAuthInfoRequest.getCode());
        wechatGetOpenIdRequest.setChannelId(channelCallCfg.getCallChannelId());
        wechatGetOpenIdRequest.setChannelType(ChannelEnum.BSPS.getChannelType());

        String respCode = RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespCode();
        String respDesc = RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc();
        DubboService dubboService = new DubboServiceImpl();
        Result<WechatGetOpenIdResponse> wechatResponse = (Result<WechatGetOpenIdResponse>) dubboService.callDubboService("wechatPubService", "getOpenId", wechatGetOpenIdRequest);
        if (null == wechatResponse) {
            rglog.error("调用微信获取用户openID服务异常！,WechatGetOpenIdResponse为空！");
            throw new BizException(respCode, respDesc);
        } else if (!wechatResponse.isSuccess() || null == wechatResponse.getResult() || !RespCodeEnum.TRANS_SUCCESS.getRespCode().equals(wechatResponse.getResult().getRespCode())) {
            if (null != wechatResponse.getResult()) {
                respCode = wechatResponse.getResult().getRespCode();
                respDesc = wechatResponse.getResult().getRespDesc();
            }
            rglog.error("调用微信获取用户openID服务异常,dubbo交易失败！");
            throw new BizException(respCode, respDesc);
        }
        WechatGetOpenIdResponse wechatGetOpenIdResponse = wechatResponse.getResult();
        response.setUserId(wechatGetOpenIdResponse.getOpenId());
        response.setNickName(wechatGetOpenIdResponse.getNickName());
        response.setUserImagePath(wechatGetOpenIdResponse.getUserImagePath());
        response.setCity(wechatGetOpenIdResponse.getCity());
        response.setCountry(wechatGetOpenIdResponse.getCountry());
        response.setProvince(wechatGetOpenIdResponse.getProvince());
        response.setUserSex(wechatGetOpenIdResponse.getSex());
        response.setUnionId(wechatGetOpenIdResponse.getUnionId());
        response.setUserPrivilege(wechatGetOpenIdResponse.getUserPrivilege());
        response.setUnionId(wechatGetOpenIdResponse.getUnionId());

        BizResponse<GetUserAuthInfoResponse> bizResponse = new BizResponse<>();

        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(response);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        GetUserAuthInfoResponse getUserAuthInfoResponse = (GetUserAuthInfoResponse) bizResponse.getResult();
        ConvertUtil.convertInput(getUserAuthInfoResponse);
    }
}
